package com.stars.easyms.redis.interceptor;

import com.stars.easyms.redis.annotion.RedisHashSet;
import com.stars.easyms.redis.exception.RedisInterceptorException;
import com.stars.easyms.base.util.GenericTypeUtil;
import com.stars.easyms.base.util.ReflectUtil;
import com.stars.easyms.base.util.TimeUtil;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p>className: RedisHashSetInterceptor</p>
 * <p>description: RedisHashSet注解拦截器</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-03-18 14:39
 */
public class RedisHashSetInterceptor extends AbstractRedisInterceptor<RedisHashSet> {

    @Override
    protected Object invoke(MethodInvocation methodInvocation, RedisHashSet redisHashSet) throws RedisInterceptorException {
        Object result = proceed(methodInvocation);
        if (isEnabled() && result != null) {
            Method pointMethod = methodInvocation.getMethod();
            Class<?> returnType = pointMethod.getReturnType();
            Type genericReturnType = pointMethod.getGenericReturnType();
            Set<String> hashKeySet = getRedisHashKey(methodInvocation);
            int hashKeySetSize = hashKeySet.size();
            boolean isInvalidReturnType = hashKeySetSize > 1 && (!Map.class.isAssignableFrom(returnType) || !String.class.isAssignableFrom(GenericTypeUtil.getGenericClass(genericReturnType, 0)));
            if (isInvalidReturnType) {
                logger.error("Method '{}' when have more than one redis hashKey, returnType should be Map<String, T>!", ReflectUtil.getMethodFullName(pointMethod));
            } else {
                String redisKey = getRedisKey(methodInvocation, redisHashSet.group());
                if (hashKeySetSize == 1) {
                    easyMsRedisTemplate.hashSet(redisKey, (String) hashKeySet.toArray()[0], result);
                } else {
                    if (redisHashSet.override()) {
                        easyMsRedisTemplate.delete(redisKey);
                    }
                    easyMsRedisTemplate.hashSet(redisKey, result);
                }
                Long expire = getExpire(methodInvocation);
                expire = expire != null ? expire : TimeUtil.parseToMilliseconds(redisHashSet.expire());
                boolean isSetExpire = expire != null && expire > 0 && (redisHashSet.resetExpire() || easyMsRedisTemplate.getExpire(redisKey, TimeUnit.MILLISECONDS) <= 0);
                if (isSetExpire) {
                    easyMsRedisTemplate.expire(redisKey, expire, TimeUnit.MILLISECONDS);
                }
            }
        }
        return result;
    }
}